/* 
 * File:   Lesson7.cpp
 * Author: jose
 * 
 * Created on March 29, 2012, 3:24 PM
 */

#include "Lesson7.h"
#include "SdlUtils.h"
#include <SDL/SDL.h>

Lesson7::Lesson7() {
}

Lesson7::Lesson7(const Lesson7& orig) {
}

Lesson7::~Lesson7() {
}

bool Lesson7::init() {
    //Initialize all SDL subsystems
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        return false;
    }

    //Set up the screen
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);

    //If there was an error in setting up the screen
    if (screen == NULL) {
        return false;
    }

    //Initialize SDL_ttf
    if (TTF_Init() == -1) {
        return false;
    }

    //Set the window caption
    SDL_WM_SetCaption("TTF Test", NULL);

    //If everything initialized fine
    return true;
}

bool Lesson7::loadFiles() {
    //Load the background image
    background = SdlUtils::loadImage("blackbackground.png");

    //Open the font
    font = TTF_OpenFont("lazy.ttf", 28);

    //If there was a problem in loading the background
    if (background == NULL) {
        return false;
    }

    //If there was an error in loading the font
    if (font == NULL) {
        return false;
    }

    //If everything loaded fine
    return true;
}

void Lesson7::cleanUp() {
    //Free the surfaces
    SDL_FreeSurface(background);
    SDL_FreeSurface(message);

    //Close the font that was used
    TTF_CloseFont(font);

    //Quit SDL_ttf
    TTF_Quit();

    //Quit SDL
    SDL_Quit();
}

int Lesson7::Run() {

    //The event structure
    SDL_Event event;

    //The color of the font
    SDL_Color textColor = {255, 255, 255};

    //Quit flag
    bool quit = false;

    //Initialize
    if (init() == false) {
        return 1;
    }

    //Load the files
    if (loadFiles() == false) {
        return 1;
    }
    
    message = TTF_RenderText_Solid( font, "My first font test", textColor);
    
    if(message == NULL)
    {
        return 1;
    }
    
    SdlUtils::applySurface(0,0,background, screen);
    SdlUtils::applySurface(screen->w/4,screen->h/2, message, screen);

    if (SDL_Flip(screen) == -1) {
        return 1;
    }

    while (!quit) {
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                quit = true;
            }
        }
    }

    cleanUp();
}